require "rexml/document"
require "iconv"
include REXML

if ARGV.length>0 then
  puts "USAGE: ruby main.rb"
  exit
end

manifest = Document.new File.new("AndroidManifest.xml")
file_channels = File.new("channels.txt", "r")
version = "V" + manifest.root.attributes["android:versionName"]
version_code = "c" + manifest.root.attributes["android:versionCode"]
date = Time.new.strftime("%Y%m%d%H%M")

cmd = "mkdir release"
system(cmd)

puts "backup manifest file"
cmd = "cp AndroidManifest.xml release/AndroidManifest_bak.xml"
system(cmd)

file_channels.each_line do |channel|
#  channel_cn = Iconv.conv("GBK//IGNORE","UTF-8//IGNORE",channel)
  channel_cn = channel
  puts channel_cn
  puts channel_cn.encoding
  org_val = manifest.root.elements["application/meta-data[@android:name='UMENG_CHANNEL']"].attributes["android:value"]
#  org_channel = Iconv.conv("UTF-8//IGNORE","GBK//IGNORE",channel_cn).chomp
  org_channel = channel_cn.chomp
  puts org_channel.encoding
  manifest.root.elements["application/meta-data[@android:name='UMENG_CHANNEL']"].attributes["android:value"] = org_channel
  manifest.root.elements["application/meta-data[@android:name='APP_CHANNEL']"].attributes["android:value"] = org_channel

  puts org_val.to_s.encoding
  #manifest.elements.each("meta-data") do |element|
  #  element.attributes["android:value"] = channel if element.attributes["android:name"] == "UMENG_CHANNEL"
  #end
  File.open("AndroidManifest.xml", 'w') do |xml_file|
    manifest.write(xml_file)
  end
  cmd = "cp AndroidManifest.xml release/AndroidManifest_" + channel.chomp + ".xml"
#  cmd_gbk = Iconv.conv("GBK//IGNORE","UTF-8//IGNORE",cmd)
  cmd_gbk = cmd
  puts cmd_gbk
  system(cmd_gbk)

  system("ant release")
  cmd = "mv bin/MainActivity-release.apk release/istar_" + date + "_" + version + "_" + version_code + "_" +org_channel + ".apk"
#  cmd_gbk = Iconv.conv("GBK//IGNORE","UTF-8//IGNORE",cmd)
  cmd_gbk = cmd
  puts cmd_gbk
  system(cmd_gbk)
  #exit
end

puts "restore manifest file"
cmd = "mv release/AndroidManifest_bak.xml AndroidManifest.xml"
system(cmd)